package de.firefligher.network.ice.messenger.server;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;

public class Connection extends Thread implements EventSender, ChatClient {
	public ChatServer server;
	public Socket client;
	public DataInputStream in;
	public PrintStream out;

	public Connection(ChatServer chatServer, Socket client) {
		this.server = chatServer;
		this.client = client;
		
		try {
			in = new DataInputStream(client.getInputStream());
			out = new PrintStream(client.getOutputStream());
		} catch (IOException e) {
			try {
				client.close();
			} catch (IOException e1) { }
			
			System.err.println("Coudn't open stream!");
			return;
		}
		
		start();
	}
	
	@SuppressWarnings("deprecation")
	public void run() {
		String line;
		
		while(true) {
			EventHandler event = null;
			
			try {
				line = in.readLine();
				if(line != null)
					event = new EventSendMessage(this, new String[] {line});
			} catch (IOException e) {
				System.err.println("Error: " + e.getMessage());
			}
			
			new Thread(event).start();
		}
	}

	@Override
	public void sendMessage(String par1String) {
		this.out.println(par1String);
	}

	@Override
	public String getInvName() {
		return "ChatClient";
	}

	@Override
	public ChatServer getServer() {
		return server;
	}
}
